﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

public class GameSaveManager : MonoBehaviour
{
    static GameSaveManager instance;

    public RecordList victoryRecord;

    private void Awake()
    {
        if (null != instance)
        {
            Destroy(gameObject);
            return;
        }
        instance = this;

        DontDestroyOnLoad(this);
    }
    public static void SaveRecord()
    {
        //判断目录路径是否存在,没有此路径就创建
        if (!Directory.Exists(Application.persistentDataPath + "/game_SaveData"))
        {
            //修改括号路径可更改为指定路径
            Directory.CreateDirectory(Application.persistentDataPath + "/game_SaveData");
        }

        BinaryFormatter formatter = new BinaryFormatter();//二进制转化

        FileStream file = File.Create(Application.persistentDataPath + "/game_SaveData/victoryRecord.txt");//创建存储文件

        string playerData = instance.PlayerDataToString(instance.victoryRecord.recordList);

        byte[] b = Encoding.UTF8.GetBytes(playerData);
        
        formatter.Serialize(file, b);//把Json数据以二进制输出到file存储文件

        file.Close();//保存文件更改
    }

    public static void LoadRecord()
    {
        BinaryFormatter bf = new BinaryFormatter();
        //判断文件路径是否存在
        if (File.Exists(Application.persistentDataPath + "/game_SaveData/victoryRecord.txt"))
        {
            //打开存储文件
            FileStream file = File.Open(Application.persistentDataPath + "/game_SaveData/victoryRecord.txt", FileMode.Open);

            byte[] playerData = (byte[])bf.Deserialize(file);

            file.Close();
            //从0下标开始获取
            string st = Encoding.UTF8.GetString(playerData, 0, playerData.Length);

            instance.StringToList(st, instance.victoryRecord.recordList);
        }
    }

    public string PlayerDataToString(List<PlayerData> dataList)
    {
        string pd = "";
        for (int i = 0; i < dataList.Count; i++)
        {
            if (null == dataList[i])
                return pd;

            string name = dataList[i].playerName;
            float record = dataList[i].playerRecord;

            pd += name + ":" + record + ";";
        }

        return pd;
    }

    public void StringToList(string playerDataString, List<PlayerData> list)
    {
        string[] pd = playerDataString.Split(';');
        for (int i = 0; i < pd.Length - 1; i++)
        {
            string[] st = pd[i].Split(':');
            PlayerData playerData = gameObject.AddComponent<PlayerData>();
            playerData.playerName = st[0];
            playerData.playerRecord = float.Parse(st[1]);
            list[i] = playerData;
        }
    }
}
